/* eslint-disable no-script-url */
import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { Button, Loading, Breadcrumb, Select, Balloon } from '@teamix/ui';
import { YunxiaoIcon, Content, Body, BodyContent } from '@alife/devops-ui';
import * as actions from '../actions/index';
import * as rootActions from '../../../actions';
import CommitInfoMedia from 'components/commitInfoMedia';
import ListEmpty from 'atComponents/ListEmpty';
import BranchAndTagSelect from 'components/branchAndTagSelect';
import { enterPage, Perf } from 'utils/track';
import TreeAndDiff from 'components/treeAndDiff';
import intl from '../../../../../../../locale';

// const comparisonMode = [ Balloon, Select
//   { label: '合并比较', value: 'Merge comparison' },
//   { label: '文件比较', value: 'File comparison' },
// ];

const comparisonMode = [
  { label: '合并比较', value: 'Merge comparison' },
  { label: '文件比较', value: 'File comparison' },
];

class Root extends Component {
  static propTypes = {
    diffs: PropTypes.arrayOf(PropTypes.object),
    commits: PropTypes.arrayOf(PropTypes.object),
    messages: PropTypes.string,
    comparisonValue: PropTypes.string,
  };

  static defaultProps = {
    diffs: [],
    commits: [],
    messages: '',
    comparisonValue: '',
  };

  componentDidMount() {
    this.getData();

    enterPage('Repo-Compare', {
      sendPerf: false,
    });
  }

  getData = () => {
    const { from, to } = this.props;
    if (from && to) {
      this.props.getCommitCompare();
    }
  };

  onExchangeClick = () => {
    const { from, to } = this.props;
    this.props.updateData({
      from: to,
      to: from,
    });

    this.getData();
  };

  onBranchChange = (key, value) => {
    this.props.updateData({
      [key]: value,
    });
  };

  handleChange = (value, type) => {
    this.setState({
      [type]: value,
    });
  };

  toggleHistory = () => {
    const { isShowCommits } = this.props;
    this.props.updateData({
      isShowCommits: !isShowCommits,
    });
  };

  toggleTip = (key) => {
    this.props.updateData({
      [key]: !this.props[key],
    });
  };

  comparisonChange = (value) => {
    this.props.comparisonChange(value);
    this.props.getCommitCompare();
  };

  renderMain = () => {
    const { isLoading, diffs, isShowCommits, commits, fromBranch, toBranch, messages } = this.props;

    if (isLoading) {
      return (
        <div className="compare-loading">
          <Loading />
        </div>
      );
    }

    if (!isLoading && commits.length && !diffs.length) {
      return (
        <div className="compare-empty">
          <Perf page="Repo-Compare" />
          <ListEmpty
            image="none"
            content={messages[0] || '不支持大改动比较'}
            description={messages[1] || null}
          />
        </div>
      );
    }

    if (!isLoading && !commits.length) {
      return (
        <div className="compare-empty">
          <Perf page="Repo-Compare" />
          <ListEmpty
            image="none"
            content={
              messages[0] ||
              intl.get({
                id: 'code-assets.projectCompare.containers.root.NoComparisonContent',
                defaultMessage: '没有比较内容',
              })
            }
            description={messages[1] || null}
          />
        </div>
      );
    }
    return (
      <React.Fragment>
        <Perf page="Repo-Compare" />
        <div className="compare-history">
          <div className="history-title">
            <div className="history-title-left">
              {intl.get(
                {
                  id: 'code-assets.projectCompare.containers.root.SubmissionHistoryCommitslength',
                  defaultMessage: '提交历史 · {commitsLength}',
                },
                { commitsLength: commits.length },
              )}
            </div>
            <div
              className="history-title-right"
              onClick={() => {
                this.toggleTip('isShowCommits');
              }}
            >
              <span>
                {!isShowCommits
                  ? intl.get({
                      id: 'code-assets.projectCompare.containers.root.PutAway',
                      defaultMessage: '收起',
                    })
                  : intl.get({
                      id: 'code-assets.projectCompare.containers.root.Expand',
                      defaultMessage: '展开',
                    })}
              </span>
              &nbsp;
              <YunxiaoIcon
                type={`arrow-${!isShowCommits ? 'up' : 'down'}-2-line`}
                className="hide-history-icon"
              />
            </div>
          </div>
          <div className="history-list" style={{ display: !isShowCommits ? 'block' : 'none' }}>
            {commits.map((commitInfo) => (
              <CommitInfoMedia condensed commitInfo={commitInfo} />
            ))}
          </div>
        </div>
        <div className="compare-tree-content">
          <TreeAndDiff
            fromBranch={fromBranch}
            commitId={toBranch}
            diffs={diffs}
            onChange={this.handleChange}
            genWatermarkimage={this.props.genWatermarkimage}
          />
        </div>
      </React.Fragment>
    );
  };

  renderContent = () => {
    const { from, to, isLoading, comparisonValue } = this.props;
    return (
      <React.Fragment>
        <div className="project-layout-wrapper-placeholder" />
        <div className="project-content compare-content full-width project-content-compare">
          <Breadcrumb>
            <Breadcrumb.Item
              link="javascript:;"
              onClick={() => {
                history.go(-1);
              }}
            >
              {intl.get({
                id: 'code-assets.projectCompare.containers.root.TheNextHigherLevel',
                defaultMessage: '上一级',
              })}
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              {intl.get({
                id: 'code-assets.projectCompare.containers.root.Comparison',
                defaultMessage: '比较',
              })}
            </Breadcrumb.Item>
          </Breadcrumb>
          <div className="compare-src-dist">
            <div className="compare-select-wrapper">
              <div className="compare-select-wrapper-dist">
                <span className="dist-text">
                  {intl.get({
                    id: 'code-assets.projectCompare.containers.root.Source',
                    defaultMessage: '源',
                  })}
                </span>
                <BranchAndTagSelect
                  value={to}
                  autoComplete
                  onChange={(value) => {
                    this.onBranchChange('to', value);
                  }}
                  needTagSearch
                  noDefaultValue
                  placeholder={intl.get({
                    id: 'code-assets.src.utils.locale.EnterToSearch',
                    defaultMessage: '请输入以搜索',
                  })}
                  className="br-select"
                  {...this.props}
                />
              </div>
              <YunxiaoIcon
                type="switch-line"
                className="compare-switch cursor"
                onClick={this.onExchangeClick}
              />

              <div className="compare-select-wrapper-src">
                <span className="src-text">
                  {intl.get({
                      id: 'code-assets.projectCompare.containers.root.Target',
                      defaultMessage: '目标',
                    })}
                </span>
                <BranchAndTagSelect
                  value={from}
                  autoComplete
                  onChange={(value) => {
                    this.onBranchChange('from', value);
                  }}
                  needTagSearch
                  noDefaultValue
                  className="br-select"
                  placeholder={intl.get({
                    id: 'code-assets.src.utils.locale.EnterToSearch',
                    defaultMessage: '请输入以搜索',
                  })}
                  {...this.props}
                />
              </div>
              <div className="compare-more-mode">
                <span style={{ marginRight: '6px' }}>
                  比较模式
                  <Balloon.Tooltip
                    align="t"
                    trigger={
                      <YunxiaoIcon type="question-line" />
                      // <Icon biz="basic" type="question-o" />
                    }
                  >
                    <div>
                      <span>比较模式说明：</span>
                      <ul>
                        <li>合并比较：比较基于源对象可以合并到目标对象的内容</li>
                        <li>文件比较：比较源和目标对象有差异的全部文件内容</li>
                      </ul>
                    </div>
                  </Balloon.Tooltip>
                </span>
                <Select
                  dataSource={comparisonMode}
                  value={comparisonValue}
                  onChange={this.comparisonChange}
                />
              </div>
              <Button
                type="primary"
                className="compare-btn"
                onClick={this.getData}
                loading={isLoading}
              >
                {intl.get({
                  id: 'code-assets.projectCompare.containers.root.Comparison',
                  defaultMessage: '比较',
                })}
              </Button>
            </div>
          </div>
          {this.renderMain()}
        </div>
      </React.Fragment>
    );
  };

  render() {
    return (
      <Body>
        <BodyContent>
          <Content>{this.renderContent()}</Content>
        </BodyContent>
      </Body>
    );
  }
}

export default connect(
  (state) => {
    return {
      ...state.project.projectCompare,
      genWatermarkimage: state.project.root.genWatermarkimage,
    };
  },
  (dispatch) => bindActionCreators({ ...rootActions, ...actions }, dispatch),
)(Root);
